<template>
  <div>
    <div class="text-right mb-4">
      <el-button type="primary" @click="visible = true">添加跟进记录</el-button>
    </div>
    <el-timeline class="h-auto" v-loading="loading">
      <template v-for="(group, groupIndex) in groupedData" :key="groupIndex" :timestamp="group.date" type="primary"
        placement="top">
        {{ group.date }}
        <el-timeline>
          <el-timeline-item v-for="(item, itemIndex) in group.items" :key="itemIndex"
            :timestamp="item.add_time.split(' ')[1] + ' ' + item.add_user_name" :color="item.background_color"
            placement="top">
            <el-card :style="{ backgroundColor: item?.background_color }">
              <p class="whitespace-pre-line">
                {{ item.remark }}
              <p v-if="item.is_visit">【约访】</p>
              </p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </template>
    </el-timeline>
    <EmptyImg v-if="groupedData.length === 0" msg="暂无跟进记录"></EmptyImg>
    <el-dialog v-model="visible" title="添加跟进记录" width="500px" destroy-on-close append-to-body>
      <AddRecord :clueId="clueId" @success="onAddSuccess" @close="visible = false" />
    </el-dialog>
  </div>
</template>

<script setup>
import { clueTraceServer } from '@/api/clue'
import { ref } from 'vue'
import AddRecord from './AddRecord.vue'
const props = defineProps({
  clueId: {
    type: Number,
  },
})
const emit = defineEmits(['success'])

// 计算属性，按日期分组数据
const groupedData = ref([])

const loading = ref(false);
const getClueRecordTimeData = async () => {
  loading.value = true
  try {
    const { data } = await clueTraceServer.get({ clue_id: props.clueId })
    const groups = {};
    (data || []).forEach((item) => {
      const date = item.add_time.split(' ')[0]
      if (!groups[date]) {
        groups[date] = { date, items: [] }
      }
      groups[date].items.push(item)
    })
    groupedData.value = Object.values(groups).sort((a, b) => new Date(b.date) - new Date(a.date))
  } catch (error) {
    console.error(error);
  }
  loading.value = false
}
getClueRecordTimeData();

const visible = ref(false)
const onAddSuccess = () => {
  getClueRecordTimeData()
  // 更新表格数据
  emit('success', true)
}
</script>
